// pages/posts/post-detail/post-detail.js
var postsData = require("../../../data/posts-data.js");
var app = getApp();

Page({

  //产生事件、捕捉事件、回调函数、处理事件

  /**
   * 页面的初始数据
   */
  data: {
    isPlayingMusic: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var postId = options.id;
    this.data.currentPostId = postId;
    var postData = postsData.postList[postId];
    this.setData({
      postData: postData
    });

    //收藏，判断是否有缓存信息，若没有点击之后就立即收藏，加入到缓存中
    var postsCollected = wx.getStorageSync('posts_collected')
    if (postsCollected) {
      var postCollected = postsCollected[postId];
      this.setData({
        collected: postCollected
      });
    } else {
      var postsCollected = {}
      postsCollected[postId] = false;
      //设置缓存
      wx.setStorageSync('posts_collected', postsCollected);
    }

    if (app.globalData.g_isPlayingMusic && app.globalData.g_currentMusicPostId === postId) {
      this.setData({isPlayingMusic : true});
    }

    this.setMusicMonitor();

  },

  //音频监视器
  setMusicMonitor: function() {
    var that = this;
    const back = wx.getBackgroundAudioManager();

    //监听背景音频播放事件
    back.onPlay(() => {
      console.log("音乐播放开始");
      that.setData({ isPlayingMusic: true });
      app.globalData.g_isPlayingMusic = true;
      app.globalData.g_currentMusicPostId = that.data.currentPostId;
    });

    //背景音频暂停事件的回调函数
    back.onPause(() => {
      console.log("音乐播放结束");
      that.setData({ isPlayingMusic: false });
      app.globalData.g_isPlayingMusic = false;
      app.globalData.g_currentMusicPostId = null;
    });

    back.onStop(() => {
      console.log("音乐播放停止");
      that.setData({ isPlayingMusic: false });
      app.globalData.g_isPlayingMusic = false;
      app.globalData.g_currentMusicPostId = null;
    })
  },


  //收藏点击事件
  onCollectionTap: function(event) {
    this.getPostsCollectedSyc();
    // this.getPostsCollectedAsy();
  },

  //自定义同步缓存方法
  getPostsCollectedSyc: function() {
    var postsCollected = wx.getStorageSync('posts_collected');
    var postCollected = postsCollected[this.data.currentPostId];

    //收藏变成未收藏，未收藏变成收藏
    postCollected = !postCollected;
    postsCollected[this.data.currentPostId] = postCollected;
    this.showToast(postsCollected, postCollected);
  },

  //自定义异步缓存方法
  getPostsCollectedAsy: function() {
    var that = this;
    wx.getStorage({
      key: "posts_collected",
      success: function(res) {
        var postsCollected = res.data;
        var postCollected = postsCollected[that.data.currentPostId];
        //收藏变成未收藏，未收藏变成收藏
        postCollected = !postCollected;
        postsCollected[that.data.currentPostId] = postCollected;
        that.showToast(postsCollected, postCollected);
      }
    })
  },

  //显示模态对话框(收藏)
  showModel: function(postsCollected, postCollected) {
    var that = this;
    wx.showModal({
      title: '收藏',
      content: postCollected ? '收藏该文章？' : "取消收藏该文章？",
      showCancel: true,
      cancelText: "取消",
      cancelColor: "#333",
      confirmText: "确认",
      confirmColor: "#405f80",
      success(res) {
        if (res.confirm) {
          //更新文章是否的缓存值
          wx.setStorageSync('posts_collected', postsCollected);
          //更新数据绑定变量，从而实现切换图片
          that.setData({
            collected: postCollected
          });
        }
      }
    })
  },

  //显示消息提示框(收藏)
  showToast: function(postsCollected, postCollected) {
    //更新文章是否的缓存值
    wx.setStorageSync('posts_collected', postsCollected);
    //更新数据绑定变量，从而实现切换图片
    this.setData({
      collected: postCollected
    });
    wx.showToast({
      title: postCollected ? "收藏成功" : "取消收藏成功",
      duration: 1000,
      icon: "success",
    })
  },

  //显示操作菜单（分享点击事件）
  onShareTap: function(event) {
    var itemList = ["分享给微信好友", "分享到朋友圈", "分享到QQ", "分享到微博"];
    wx.showActionSheet({
      itemList: itemList,
      itemColor: "#405f80",
      success: function(res) {
        // res.cancel  用户是不是点击了取消按钮
        // res.tapIndex 数组元素的序号，从零开始
        wx.showModal({
          title: '用户' + itemList[res.tapIndex],
          content: "用户是否取消？" + res.cancel + "现在无法实现分享功能，什么时候能支持呢"
        });
      }
    })
  },


  //音乐播放点击事件
  onMusicTap: function() {
    var currentPostId = this.data.currentPostId;
    var isPlayingMusic = this.data.isPlayingMusic;
    var postData = postsData.postList[currentPostId];

    const backgroundAudioManager = wx.getBackgroundAudioManager()

    if (isPlayingMusic) {
      //暂停音乐播放 
      backgroundAudioManager.pause();
      this.setData({
        isPlayingMusic: false
      })
      this.data.isPlayingMusic = false;
    } else {
      backgroundAudioManager.title = postData.music.title
      backgroundAudioManager.epname = postData.music.title
      backgroundAudioManager.singer = postData.music.author
      backgroundAudioManager.coverImgUrl = postData.music.coverImg
      // 设置了 src 之后会自动播放
      backgroundAudioManager.src = postData.music.url
      this.setData({
        isPlayingMusic: true
      })
    }
  },
})